package com.ys.sboot.hystrix.arch;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import rx.Observable;
import rx.schedulers.Schedulers;

import java.io.IOException;
import java.util.List;

/**
 * <p>@description:</p>
 * <p>
 * 批量
 * <p>
 * HystrixCommand:用来获取一条数据的
 * HystrixObservableComand 用来获取多条数据
 *
 * @author yangshuang
 * @version 1.0
 * @date 2018/4/15 下午6:45
 */
public class ObservableCommondHelloWorld extends HystrixObservableCommand<String> {


    private List<String> names;

    public ObservableCommondHelloWorld(List<String> names) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));

        this.names = names;
    }

    @Override
    protected Observable<String> construct() {
        return Observable.create((Observable.OnSubscribe<String>) subscriber -> {
            if (!subscriber.isUnsubscribed()) {

                for (String name : names) {
                    String url = "http://127.0.0.1:8082/logBack/reqLogBack?name=" + name;
                    CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
                    HttpGet httpGet = new HttpGet(url);
                    String srtResult = null;
                    HttpResponse httpResponse = null;
                    try {
                        httpResponse = httpCilent.execute(httpGet);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        try {
                            srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println(srtResult);
                    } else if (httpResponse.getStatusLine().getStatusCode() == 400) {
                        //..........
                    } else if (httpResponse.getStatusLine().getStatusCode() == 500) {
                        //.............
                    }
                    subscriber.onNext(srtResult);
                }

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io());
    }
}
